package sivan.letcode;

import java.util.concurrent.atomic.AtomicInteger;

public class LeakyBucket {

    // 桶的容量
    private int capacity;
    //统计桶请求数
    private AtomicInteger water = new AtomicInteger(0);
    //水滴流出的速率。1000毫秒为单位
    private int leakRate;
    // 第一次请求之后,木桶在这个时间点开始漏水
    private long leakTimeStamp;

    public LeakyBucket(int leakRate, int capacity) {
        this.leakRate = leakRate;
        this.capacity = capacity;
    }

    public boolean acquire() {
        // 如果是空桶，就当前时间作为桶开是漏出的时间
        if (water.get() == 0) {
            leakTimeStamp = System.currentTimeMillis();
            water.incrementAndGet();
            return capacity != 0;
        }

        long c = System.currentTimeMillis() - leakTimeStamp;
        //漏水并计算剩余水量
        int waterLeft = water.get() - (int) (c / 1000) * leakRate;
        water.set(Math.max(waterLeft, 0));
        leakTimeStamp = System.currentTimeMillis();
        // 尝试加水,并且水还未满
        if ((water.get()) < capacity) {
            water.addAndGet(1);
            return true;
        } else {
            // 水满，拒绝加水
            return false;
        }
    }
}
